<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Tools\BookOnSale;
use App\Models\Book;

use App\Models\BookRecommendPosition;
use App\Models\Category;
use Carbon\Carbon;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\Facades\Request;
use DB;
use Illuminate\Support\Facades\Input;

class BooksController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('图书列表');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('修改图书');

            $content->body($this->form()->edit($id));
        });
    }

    public function update($id)
    {
        return $this->form()->update($id);
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('添加图书');

            $content->body($this->form());
        });
    }

    public function store()
    {
        return $this->form()->store();
    }

    public function destroy($id)
    {
        //$this->form()->destroy()
        $arr = explode(',',$id);
        Book::whereIn('id',$arr)->update(['deleted'=>1,'deleted_at'=>Carbon::now()]);
        return ['status'=>true,'message'=>'删除成功'];
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Book::class, function (Grid $grid) {
            $grid->model()->onSale(Request::get('on_sale'));
            $grid->model()->where('deleted', 0);

            //$grid->id('ID')->sortable();
            //$grid->title('图书名称');
            $grid->image('封面')->image(config('app.qiniu_image_domain'),150,150);
            /*$grid->title('图书名称')->display(function($text) {
                return str_limit($text, 48, '...');
            });*/
            $grid->title('图书名称')->style('width:160px');

            $grid->category_parent_id('一级分类')->display(function($value) {
                $category = Category::query()->where('id',$value)->first();
                if(!empty($category))
                {
                    return $category->title;
                }
                return '';
            });
            $grid->category_id('二级分类')->display(function($value) {
                $category = Category::query()->where('id',$value)->first();
                if(!empty($category))
                {
                    return $category->title;
                }
                return '';
            });
            /*$grid->book_recommend_positions('推荐位置')->display(function($value) {
                $arr = [];
                if(!empty($value) && is_array($value))
                {
                    foreach ($value as $v)
                    {
                        $arr[] = $v['name'];
                    }
                }

                return implode(',',$arr);
            });*/

            $grid->author('作者')->style('width:160px');
            $grid->store('库存')->sortable()->editable();
            $grid->total_read_num('租阅总数');
            $grid->real_user_read_num('真实借阅')->sortable();
            $grid->system_user_read_num('系统借阅')->sortable()->editable();
            $grid->douban_score('豆瓣分');
            $grid->column('book_publish_info.isbn','ISBN');

            $states = [
                'on'  => ['value' => 1, 'text' => '上架', 'color' => 'success'],
                'off' => ['value' => 2, 'text' => '下架', 'color' => 'danger'],
            ];
            $grid->on_sale('上架状态')->switch($states);
            //$grid->switch('on_sale', '是否上架')->states($states);

            /*$grid->on_sale('上架状态')->display(function ($value) {
                return $value == 1 ? '已上架' : '已下架';
            });*/

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->like('title', '商品名称');
                $filter->equal('category_parent_id', '一级分类')
                    ->select(Category::getSelectOptions())
                    ->load('category_id', '/api/admin/second/categories');

                $filter->equal('category_id', '二级分类')->select();

                $filter->where(function ($query) {

                    $query->whereHas('book_publish_info', function ($query) {
                        //$query->where('address', 'like', "%{$this->input}%")->orWhere('email', 'like', "%{$this->input}%");
                        $query->where('isbn', "{$this->input}");
                    });

                }, 'ISBN');
            });

            $grid->tools(function ($tools) {
                $tools->append(new BookOnSale());
            });

            $grid->actions(function ($actions) {
                $actions->disableView();
            });
            $grid->disableExport();
            //$grid->created_at();
            //$grid->updated_at();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Book::class, function (Form $form) {
            $form->display('id', 'ID');

            $form->text('title', '商品名称')->rules('required');
            $form->text('author', '作者')->rules('required');
            $form->image('image', '封面图片')->rules('required|image')->uniqueName();

            /*$form->image('image','封面图片')->name(function ($file) {
                return getPicUniqueName().'.'.$file->guessExtension();
            })->removable()->rules('required|image');*/

            $form->text('douban_score', '豆瓣分')->rules('required|numeric|min:0|max:10')->default('0.00');
            $form->text('store', '库存')->rules('required|integer|min:0');
            $form->text('system_user_read_num', '系统租阅人数')->rules('required|integer|min:0');

            $form->select('category_parent_id','一级分类')->options(Category::getSelectOptions())->load('category_id', '/api/admin/second/categories')->rules('required');
            $form->select('category_id','二级分类')->options(function ($category_id) {
                return Category::options($category_id);
            })->rules('required');


            //$form->radio('recommend_position_id','推荐位置')->options(['0' => '不推荐', '1'=> '豆瓣高分', '2' => '小编力荐', '3' => '最新出版'])->default('m');
            $form->checkbox('book_recommend_positions','推荐位置')->options(BookRecommendPosition::getSelectOptions());

            $form->editor('intro', '简介')->rules('required');
            $form->editor('catalog', '目录')->rules('required');

            $states = [
                'on'  => ['value' => 1, 'text' => '上架', 'color' => 'success'],
                'off' => ['value' => 2, 'text' => '下架', 'color' => 'danger'],

            ];

            $form->switch('on_sale', '是否上架')->states($states)->default(1);

            $form->divide('real_user_read_num');

            $form->text('book_publish_info.writer','著者')->rules('required');
            $form->text('book_publish_info.publish_house','出版社')->rules('required');
            $form->text('book_publish_info.isbn','ISBN')->rules('required');
            $form->text('book_publish_info.publish_num','版次')->rules('required|integer');
            $form->text('book_publish_info.package','包装')->rules('required');
            $form->text('book_publish_info.book_size','开本')->rules('required');
            $form->text('book_publish_info.publish_time','出版时间')->rules('required');
            $form->text('book_publish_info.use_paper','用纸')->rules('required');
            $form->text('book_publish_info.page_sizes','页数');
            //$form->text('book_publish_info.package_num','套装数量')->rules('required|integer');
            $form->text('book_publish_info.language','语种');

            $form->tools(function (Form\Tools $tools) {
                $tools->disableView();
                $tools->disableDelete();
            });


            //$form->display('created_at', 'Created At');
            //$form->display('updated_at', 'Updated At');
            //保存后回调
            $form->saved(function (Form $form) {
                $id = $form->model()->id;
                $total_read_num = $form->model()->real_user_read_num + $form->model()->system_user_read_num;
                DB::table('books')->where('id',$id)->update(['total_read_num'=>$total_read_num]);
                /*DB::table('book_category_parent_relations')->where('book_id',$id)->delete();
                DB::table('book_category_parent_relations')->insert([
                    'book_id' => $id,
                    'category_parent_id' => $form->model()->category_parent_id
                ]);*/
            });
        });
    }
}
